import { RouteRecordRaw } from 'vue-router'
import router from './index'
import asyncRoutes from './asyncRoutes'

function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
  return key in object
}

function filtersRoutes(menus: any[]): RouteRecordRaw[] {
  const ret: RouteRecordRaw[] = []
  if (!menus || !menus.length) {
    return []
  }

  menus.forEach((menu) => {
    const { name, code, path, iconClass } = menu

    if (isValidKey(code, asyncRoutes)) {
      const temp: RouteRecordRaw = {
        name: code,
        path,
        meta: { icon: iconClass, title: name },
        component: asyncRoutes[code],
        redirect: '',
      }
      ret.push(temp)
    }

    if (menu?.children?.length) ret.push(...filtersRoutes(menu.children))
  })
  return ret
}

export function addRoutes(menus: any[]) {
  const routes = filtersRoutes(menus)
  routes.push({ path: '/:catchAll(.*)', redirect: '/error/404' })
  routes.forEach((route: RouteRecordRaw) => {
    router.addRoute('Layout', route)
  })
}
